package cn.hfatec.shms.security;

import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.system.user.dao.UserDao;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.user.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户验证
 *
 * @author: panwb
 * <p/>
 * Date: 14-3-7
 * Time: 下午2:10
 */

public class VasUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";

    @Resource(name = "UserDao")
    private UserDao userDao;
    @Resource(name = "UserService")
    private UserService userService;
    private RememberMeServices rememberMeServices;

    @MysqlDataSource
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);
        String password = obtainPassword(request);

        String encodePassword = DigestUtils.md5Hex(password);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        //用户信息

        User user = userService.getUserForLogin(username);

        if (user == null) {
            throw new AuthenticationServiceException(ShmsConstant.LOGIN_ERROR_USERNAME);
        }
        if (!user.getPassword().equals(encodePassword)) {
            throw new AuthenticationServiceException(ShmsConstant.LOGIN_ERROR_PASSWORD);
        }

        HttpSession session = request.getSession();
        session.setAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME, user);
        request.getSession().setAttribute(ShmsConstant.MENU_CACHE, null);

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        setDetails(request, authRequest);
        Authentication authentication = this.getAuthenticationManager().authenticate(authRequest);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        rememberMeServices.loginSuccess(request, response, authentication);

        return authentication;

    }

    /**
     * 获取密码
     *
     * @param request
     * @return
     */
    @MysqlDataSource
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(PASSWORD);
    }

    /**
     * 获取用户名
     *
     * @param request
     * @return
     */
    @MysqlDataSource
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(USERNAME);
    }

    @Override
    @MysqlDataSource
    public void setRememberMeServices(RememberMeServices rememberMeServices) {
        this.rememberMeServices = rememberMeServices;
    }
}
